<?php

class Pldkp_Controller_Action extends Zend_Controller_Action
{
    protected $_flashMessenger;
    protected $_redirector;
    protected $_user;
    
    public function init() 
    {
        $this->_flashMessenger  = $this->_helper->getHelper('FlashMessenger');
        $this->_redirector = $this->_helper->getHelper('Redirector');
        $this->_user = Zend_Registry::getInstance()->user;
    }
    
    
    /**
     * Make sure that layout and viewrendere is disabled for ajax requests.
     */
    public function preDispatch()
    {
        if ($this->_request->isXmlHttpRequest()) {
            $this->_helper->layout()->disableLayout();
            $this->_helper->viewRenderer->setNoRender(true);
        }
        
        return parent::preDispatch();
    }
    
    /**
     * This function is highly suspicious, but just tries to ease the job og redirecting in a controller.
     * 
     * @param array|string $url
     */
    protected function redirect($url)
    {
        if (is_array($url)) {
            if (!isset($url['module'])) {
                $url['module'] = $this->_request->getModuleName();
            }
            if (!isset($url['controller'])) {
                $url['controller'] = $this->_request->getControllerName();
            }
            if (!isset($url['action'])) {
                $url['action'] = $this->_request->getActionName();
            }
            
            $router = Zend_Controller_Front::getInstance()->getRouter();
            $url = $router->assemble($url, null, true, true);
        }
        
        $this->_redirect($url, array('prependBase' => false));
    }
    
    protected function setInstantFlashMessage($message)
    {
        $this->view->flashMessage = $message;
    }

    protected function setFlashMessage($message)
    {
        $this->_flashMessenger->addMessage($message);
    }

    protected function assignFlash()
    {
        $messages = $this->_flashMessenger->getMessages();
        if (!empty($messages)) {
            $this->view->flashMessage = $messages[0];
        }
    }

    public function postDispatch()
    {
        parent::postDispatch();
        $this->assignFlash();
    }
}